const { prisma } = require('../config/prisma');

class ServiceCategoryPrisma {
  constructor(data) {
    this.id = data.id;
    this.name = data.name;
    this.icon = data.icon;
    this.description = data.description;
    this.sort_order = data.sort_order;
    this.is_active = data.is_active;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  /**
   * 获取所有活跃的服务分类
   * @returns {Promise<ServiceCategoryPrisma[]>}
   */
  static async findAllActive() {
    const categories = await prisma.service_categories.findMany({
      where: { is_active: true },
      orderBy: { sort_order: 'asc' }
    });
    return categories.map(category => new ServiceCategoryPrisma(category));
  }

  /**
   * 根据ID查找服务分类
   * @param {number} id 分类ID
   * @returns {Promise<ServiceCategoryPrisma|null>}
   */
  static async findById(id) {
    if (id === null || id === undefined) {
      return null;
    }

    const category = await prisma.service_categories.findUnique({
      where: { id: Number(id) }
    });
    return category ? new ServiceCategoryPrisma(category) : null;
  }

  /**
   * 创建新的服务分类
   * @param {Object} data 分类数据
   * @returns {Promise<ServiceCategoryPrisma>}
   */
  static async create(data) {
    const category = await prisma.service_categories.create({
      data: {
        name: data.name,
        icon: data.icon,
        description: data.description,
        sort_order: data.sort_order || 0,
        is_active: data.is_active !== undefined ? data.is_active : true
      }
    });
    return new ServiceCategoryPrisma(category);
  }

  /**
   * 更新服务分类
   * @param {Object} data 更新数据
   * @returns {Promise<ServiceCategoryPrisma>}
   */
  async update(data) {
    const updatedCategory = await prisma.service_categories.update({
      where: { id: this.id },
      data: {
        name: data.name !== undefined ? data.name : this.name,
        icon: data.icon !== undefined ? data.icon : this.icon,
        description: data.description !== undefined ? data.description : this.description,
        sort_order: data.sort_order !== undefined ? data.sort_order : this.sort_order,
        is_active: data.is_active !== undefined ? data.is_active : this.is_active,
        updated_at: new Date()
      }
    });
    
    // 更新当前实例
    Object.assign(this, updatedCategory);
    return this;
  }

  /**
   * 删除服务分类（软删除，设置为非活跃）
   * @returns {Promise<ServiceCategoryPrisma>}
   */
  async delete() {
    return await this.update({ is_active: false });
  }

  /**
   * 序列化为普通对象
   * @returns {Object}
   */
  toJSON() {
    return {
      id: this.id,
      name: this.name,
      icon: this.icon,
      description: this.description,
      sort_order: this.sort_order,
      is_active: this.is_active,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}

module.exports = ServiceCategoryPrisma;